const numberMap = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
const unitMap = ["", "十", "百", "千", "万", "亿"];

export function numberToChinese(num: number) {
  if (num === 0) return "零";
  const digits = String(num).split("").reverse().map(Number);
  // console.log(digits);
  const units: string[] = [];
  let prevDigitWasZero = false; // 标记前一个数字是否是零

  for (let i = 0; i < digits.length; i++) {
    const digit = digits[i];
    let unitIndex = 0;
    let unit = "";
    if (i < 4) {
      unitIndex = i % 4;
      unit = unitMap[unitIndex];
    } else {
      unit = `${i % 4 == 0 ? unitMap[4] : unitMap[i % 4]}`;
    }
    if (digit === 0) {
      prevDigitWasZero = true;
      if (i > 0 && digits[i + 1] !== 0) {
        units.push("零");
      }
      continue;
    } else {
      prevDigitWasZero = false;
      // 添加单位
      units.push(unit);
      // 添加数字
      units.push(numberMap[digit]);
    }
  }

  // 如果最高位是零（仅当整个数字是零时除外），则删除
  if (units[0] === "零" && units.length > 1) {
    units.shift();
  }

  // 反转数组以得到正确的顺序
  units.reverse();

  return units.join("");
}

export const speak = (str: string) => {
  // console.log(window.speechSynthesis.getVoices());
  speechSynthesis.cancel();
  const instance = new SpeechSynthesisUtterance(str);
  instance.rate = 0.8;
  speechSynthesis.speak(instance);
};
